
import EXIF from "../../components/compress-image/exif.js";
//var EXIF = require("./exif.js");
class CompressImage{
	base64Image(param) {
	    var fileInput = param.file;
	    
	    var widthInput = param.width ? param.width : 750;
	
	    var ratioInput = param.ratio ? param.ratio : 0.75;
	
	    var callback = param.callback ? param.callback : null;
	   		
	    if (!window.FileReader) {
	        alert("请升级浏览器");
	        return;
	    }
	    //var file   = fileInput.files[0];
		var file   = fileInput;
		// console.log("这是file文件",file);
	    var reader = new FileReader();
	
	    /*判断图片方向*/
	    var orientation = null;
	    EXIF.getData(file, function () {
	        //EXIF.getAllTags(this);
	        orientation = EXIF.getTag(this, 'Orientation');
	        reader.readAsDataURL(file);
	    });
	
	    reader.onloadstart = function () {
	    };
	    reader.onerror     = function () {
	    };
	    reader.onload = function () {
	        /*创建新的图片JS对象*/
	        fileInput.value="";
	
	        /*创建新的图片JS对象*/
	        var image    = new Image();
	        image.src    = this.result;
	        image.onload = function () {
	            var canvas = document.createElement("canvas");
	            var scale  = image.width / image.height;
	            if (orientation == 6) {
	                //右转 90
	                canvas.width  = image.height < widthInput ? image.height : widthInput;
	                canvas.height = parseInt(canvas.width * scale);
	                canvas.getContext("2d").rotate(90 * Math.PI / 180);
	                canvas.getContext("2d").drawImage(image, 0, 0, image.width, image.height, 0, -canvas.width, canvas.height, canvas.width);
	            } else if (orientation == 8) {
	                //左转 90
	                canvas.width  = image.height < widthInput ? image.height : widthInput;
	                canvas.height = parseInt(canvas.width * scale);
	                canvas.getContext("2d").rotate(-90 * Math.PI / 180);
	                canvas.getContext("2d").drawImage(image, 0, 0, image.width, image.height, -canvas.height, 0, canvas.height, canvas.width);
	            } else if (orientation == 3) {
	                //右转 180
	                canvas.width  = image.width < widthInput ? image.width : widthInput;
	                canvas.height = parseInt(canvas.width / scale);
	                canvas.getContext("2d").translate(canvas.width, 0);
	                canvas.getContext("2d").scale(-1, 1);
	                canvas.getContext("2d").translate(0, canvas.height);
	                canvas.getContext("2d").scale(1, -1);
	                canvas.getContext("2d").drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
	            } else {
	                //正常
	                canvas.width  = image.width < widthInput ? image.width : widthInput;
	                canvas.height = parseInt(canvas.width / scale);
	                canvas.getContext("2d").drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
	            }
	            var imageUrl = canvas.toDataURL("image/jpeg", ratioInput);
	
	            if (callback) {
	                callback(imageUrl)
	            }
	        };
	    };
	};
	
	
	
	
}

/**
	 * desc 获取图片信息，使用exif.js库 
	 * @param {Object} file 上传的图片文件
	 * @param {String} tag 需要获取的信息 例如：'Orientation'旋转信息
	 * @return {Promise} 读取是个异步操作，返回指定的图片信息
	 **/
export const getImageTag = (file, tag, suc) => {
		if (!file) return 0;
		return new Promise((resolve, reject) => {
			/ eslint-disable func-names */
			// 箭头函数会修改this，所以这里不能用箭头函数
			let imgObj = new Image()
			imgObj.src = file
			// console.log("element",imgObj)
			/* var img = document.createElement("img");  
			img.setAttribute("src", file);
			//判断图片是否已经加载完，如果已经加载完，则执行下面的函数。  
		    img.addEventListener("load", function() {  
			  let ret = EXIF.getData(img, function() {  //调用EXIF解决，图片旋转90的问题  
				  var orientation = EXIF.getAllTags(this).Orientation;
				  console.log("图片角度",orientation);
			  });  
			  console.log("获取图片信息成功?",ret);
		    })  
			return; */
			uni.getImageInfo({
				src: file,
				success(res) {
					let ret = EXIF.getData(imgObj, function () {
						EXIF.getAllTags(this);
						let or = EXIF.getTag(this,'Orientation');//这个Orientation 就是我们判断需不需要旋转的值了，有1、3、6、8
						resolve(suc(or))
					});
					// console.log("exif获取图片信息成功?",ret);
				},
				fail(e) {
					console.log("获取图片信息失败",e);
				}
			})
			
		});
	};
	
	
export const comprossImage = async (imgSrc, maxWidth, func) => {
	if(!imgSrc) return 0;
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
		src: imgSrc,
		success(res) {
			let img = new Image();
			img.src = res.path;
			// console.log(img)
			let canvas = document.createElement('canvas');  
			let obj = new Object();  
			obj.img = img;  
			obj.canvas = canvas;  
			resolve(func(obj));  
			}  
		});  
	})
}
	/**
	 * 旋转图片
	 * 
	 */
export const rotateImg = (img, direction, canvas, times = 1) => {
		// console.log('开始旋转')
		//最小与最大旋转方向，图片旋转4次后回到原方向
		var min_step = 0;
		var max_step = 3;
		if (img == null)return;
		
		//img的高度和宽度不能在img元素隐藏后获取，否则会出错    
		var height = img.height;    
		var width = img.width;    
		let maxWidth = 500;  
		let canvasWidth = width; //图片原始长宽  
		let canvasHeight = height;  
		let base = canvasWidth/canvasHeight;  
		// console.log(maxWidth);  
		if(canvasWidth > maxWidth){  
		    canvasWidth = maxWidth;  
		    canvasHeight = Math.floor(canvasWidth/base);  
		}  
		width = canvasWidth;  
		height = canvasHeight;  
		var step = 0;    
		
		if (step == null) {    
		  step = min_step;    
		}    
		if (direction == 'right') {    
		  step += times;    
		  //旋转到原位置，即超过最大值    
		  step > max_step && (step = min_step);    
		} else if(direction == 'left'){    
		  step -= times;    
		  step < min_step && (step = max_step);    
		} else {    //不旋转  
		    step = 0;  
		}  
		
		//旋转角度以弧度值为参数    
		var degree = step * 90 * Math.PI / 180;    
		var ctx = canvas.getContext('2d');    
		// console.log(degree)  
		// console.log(step)  
		switch (step) {      
		  case 1:    
		    console.log('右旋转 90度')  
		    canvas.width = height;    
		    canvas.height = width;    
		    ctx.rotate(degree);    
		    ctx.drawImage(img, 0, -height, width, height);    
		    break;    
		  case 2:    
		    //console.log('旋转 180度')  
		    canvas.width = width;    
		    canvas.height = height;    
		    ctx.rotate(degree);    
		    ctx.drawImage(img, -width, -height, width, height);    
		    break;    
		  case 3:    
		    console.log('左旋转 90度')  
		    canvas.width = height;    
		    canvas.height = width;    
		    ctx.rotate(degree);    
		    ctx.drawImage(img, -width, 0, width, height);  
		    break;    
		  default:  //不旋转  
		    canvas.width = width;  
		    canvas.height = height;  
		    ctx.drawImage(img, 0, 0, width, height);  
		    break;  
		}  
		let baseStr = canvas.toDataURL("image/jpeg", 1);
		/* let blobStr = canvas.toBlob(function(blob) {
			let url = URL.createObjectURL(blob);
			console.log("转换为blob",url);
		},"image/jpeg",1) */
		return baseStr; 
	}
export default new CompressImage();